<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="form" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="员工名称">
          <el-input
            v-model="queryParams.keywords"
            placeholder="员工名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button type="success" @click="openDialog()"
          ><i class="el-icon-circle-plus"></i> 新增</el-button>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i class="el-icon-delete"></i> 删除</el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" width="55" prop="dataIndex"/>
        <el-table-column label="姓名" prop="name"/>
        <el-table-column label="个人码" prop="code"/>
        <el-table-column label="电话" prop="phone"/>
        <el-table-column label="邮箱" prop="email"/>
        <el-table-column label="创建时间" prop="createTimeText"/>
        <el-table-column fixed="right" label="操作"  min-width="280" width="280">
          <template #default="scope">
            <el-button
              type="warning"
              size="small"
              link
              @click="openDialog(scope.row.id)"
            ><i class="el-icon-edit"></i> 编辑</el-button>
            <el-button
              type="success"
              size="small"
              link
              @click="openPromotionDialog(scope.row)"
            ><i class="el-icon-edit"></i> 推广码</el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            ><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 字典表单弹窗 -->
    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      width="500px"
      :before-close="closeDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="邮箱" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="promotionDialog.visible" :title="promotionDialog.title" width="900px" :before-close="closePromotionDialog" :close-on-click-modal="false">
      <el-button type="success" @click="openAddPromotionDialog()" style="margin-bottom: 8px;"><i class="el-icon-circle-plus"></i> 新增推广码</el-button>
      <el-table v-loading="loading" :data="employeePromotionList" highlight-current-row border style="height: 400px;">
        <el-table-column label="序号" width="55" prop="dataIndex"/>
        <el-table-column label="所属公众号" prop="wxMpName"/>
        <el-table-column label="推广码类型" prop="sceneTypeText"/>
        <el-table-column label="创建时间" prop="createTimeText"/>
        <el-table-column fixed="right" label="操作"  min-width="220" width="260">
          <template #default="scope">
            <el-button
              type="warning"
              size="small"
              link
              @click="openPromotionDetailDialog(scope.row)"
            ><i class="el-icon-view"></i> 查看 & 下载推广码</el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handlePromotionDelete(scope.row.id)"
            ><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog :visible.sync="addPromotionDialog.visible" :title="addPromotionDialog.title" width="350px" :before-close="closeAddPromotionDialog" :close-on-click-modal="false">
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="90px">
        <el-form-item label="推广类型" prop="sceneType">
          <el-select v-model="sceneType" placeholder="请输入推广类型">
            <el-option label="菌佑管家 - FMT问卷" value="MANAGE_FMT_SURVEY"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属公众号" prop="wxMpId">
          <el-select v-model="wxMpId" placeholder="请输入所属公众号">
            <el-option :label="item.name" :value="item.id" v-for="item in wxMpList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addPromotion">确 定</el-button>
          <el-button @click="closeAddPromotionDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="wxQrCodeDetailDialog.visible" :title="wxQrCodeDetailDialog.title" width="470px" :close-on-click-modal="false">
      <iframe :src="wxQrCodeData.qrUrl" style="width: 100%; height: 430px; border: 0px;"></iframe>
    </el-dialog>

  </div>
</template>

<script>

import employeeApi from '@/api/aliyun/ops/employee'
import employeePromotionApi from '@/api/aliyun/ops/employeePromotion'
import wxMpApi from '@/api/aliyun/thirdparty/wxMp';
import { formatDate } from '@/utils/formatTime'
export default {
	name: 'promotionIndex',
	data() {
		return {
			queryParams: {
        keywords: '',
        pageNum: 0,
        pageSize: 10,

      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      dialog: {},
      formData: {},
      rules: {},

      addPromotionDialog: {},
      promotionDialog: {},
      checkedEmployee: {},
      employeePromotionList: [],
      sceneType: '',
      wxMpId: '',
      wxMpList: [],
      
      wxQrCodeDetailDialog: {},
      wxQrCodeData: {},

      scenceTypeMap: {
        MANAGE_FMT_SURVEY: '菌佑管家 - FMT问卷'
      },
		};
	},
  methods: {
    handlePromotionDelete (id) {

      this.$confirm('此操作将永久删除推广码，可能会影响已有得推广二维码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        employeePromotionApi.delete(id).then(res => {
          this.$message({message: '员工推广码删除成功！', type: 'danger'});
          this.openPromotionDialog(this.checkedEmployee);
        })
      }).catch(() => {});
    },
    openPromotionDetailDialog (row) {
      this.$set(this.wxQrCodeDetailDialog, 'visible', true);
      this.$set(this.wxQrCodeDetailDialog, 'title', '查看公众号带参二维码');
      row.qrUrl = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' + row.ticket
      this.wxQrCodeData = row;
    },
    addPromotion () {
      employeePromotionApi.add({
        employeeId: this.checkedEmployee.id,
        employeeCode: this.checkedEmployee.code,
        sceneType: this.sceneType,
        wxMpId: this.wxMpId
      }).then(res => {
        this.$message({message: '员工推广码添加成功！', type: 'success'});
        this.closeAddPromotionDialog();
        this.openPromotionDialog(this.checkedEmployee);
      })
    },
    openPromotionDialog (row) {
      this.checkedEmployee = row;
      this.$set(this.promotionDialog, 'visible', true);
      this.$set(this.promotionDialog, 'title', '推广码列表');
      employeePromotionApi.list(row.id).then(res => {
        let index = 1;
        res.data.forEach(v => {
          v.sceneTypeText = this.scenceTypeMap[v.sceneType];
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.dataIndex = index++;
        })
        this.employeePromotionList = res.data;
      })
    },
    closePromotionDialog () {
      this.$set(this.promotionDialog, 'visible', false);
    },
    openAddPromotionDialog (id) {
      this.$set(this.addPromotionDialog, 'visible', true);
      this.$set(this.addPromotionDialog, 'title', '新增推广码');
      wxMpApi.list().then(res => {
        this.wxMpList = res.data;
      })
    },
    closeAddPromotionDialog () {
      this.$set(this.addPromotionDialog, 'visible', false);
    },
    handleQuery() {
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize
      };
      employeeApi.page(params).then((res) => {
        let data = res.data;
        let that = this;
        let index = 1
        data.content.forEach((v) => {
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
          v.dataIndex = index++;
        });
        this.dataList = data.content;
        
        this.total = data.count;
        this.loading = false;
      }).catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
      };
      this.handleQuery();
    },
    
    addOrUpdate() {
      let that = this;
      if (this.formData.id) {
        employeeApi.update(this.formData).then((res) => {
          this.$message({message: '员工信息更新成功！', type: 'success'});
          that.closeDialog();
        });
      } else {
        employeeApi.add(this.formData).then((res) => {
          this.$message({message: '员工信息添加成功！', type: 'success'});
          that.closeDialog();
        });
      }
    },
    openDialog(id) {
      this.$set(this.dialog, 'visible', true);
      let that = this;
      if (id) {
        this.$set(this.dialog, 'title', '编辑员工信息');
        employeeApi.get(id).then((res) => {
          let data = res.data;
          that.formData = data;

        });
      } else {
        this.$set(this.dialog, 'title', '新增员工信息');
        that.formData = {};
      }

    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.handleQuery();
    },
    handleDelete(id) {
      if (id) {
        employeeApi.delete(id).then((res) => {
          this.$message({message: '员工信息删除成功！', type: 'success'});
          this.handleQuery();
        });
      } else {
        this.$message.error('暂不支持批量删除员工信息！');
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
  },
  created() {
    this.handleQuery();
  }
};
</script>

<style scoped>
.el-pagination {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}
</style>